
from django.shortcuts import render
from django.utils import timezone
from rest_framework import status, mixins, serializers
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from answers.models import Label, Question, Reply
from answers.serializers.labels import LabelSerializer, NewQuestionSerializer, DetailedLabelSerializer
from answers.serializers.question import PublishQuestionSerializers, \
    ObtainDetailQuestionSerializers, ReplyQuestionSerializers
from users.models import User


class GetLabelsInfoView(mixins.ListModelMixin,GenericViewSet):
    '''获取标签label信息类'''
    serializer_class = LabelSerializer

    queryset = Label.objects.all()

    pagination_class = None


class GetDetailedLabelsInfoView(mixins.RetrieveModelMixin,GenericViewSet):
    '''获取标签label信息类'''
    serializer_class = DetailedLabelSerializer

    queryset = Label.objects.all()

    pagination_class = None

    lookup_value_regex = '\d+'


class GetLabelsUserInfoView(ListAPIView):
    '''获取⽤用户关注的标签'''
    permission_classes = [IsAuthenticated]

    serializer_class = LabelSerializer

    def list(self, request, *args, **kwargs):

        queryset = Label.objects.filter(users=request.user.id)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    pagination_class = None


class NewQuestionView(APIView):
    '''获取最新被回答过的问题列列表视图'''

    def get(self,request,pk):

        now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)

        if pk == "-1":

            now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)

            question = Question.objects.filter(replytime__gte=now_date-timezone.timedelta(days=30))

            serializers = NewQuestionSerializer(question,many=True)

        else:

            question = Question.objects.filter(labels=pk,replytime__gte=now_date-timezone.timedelta(days=30))

            serializers = NewQuestionSerializer(question,many=True)

        return Response(serializers.data,status=status.HTTP_200_OK)


class HotQuestionView(APIView):
    '''热⻔门回答的问题视图'''

    def get(self,request,pk):

        if pk == '-1':

            question = Question.objects.filter(thumbup__gte=10)

            serializers = NewQuestionSerializer(question, many=True)

        else:

            question = Question.objects.filter(labels=pk,thumbup__gte=10)

            serializers = NewQuestionSerializer(question, many=True)

        return Response(serializers.data, status=status.HTTP_200_OK)


class WaitQuestionView(APIView):
    '''等待回答的问题'''

    def get(self,request,pk):

        if pk == '-1':

            question = Question.objects.filter(reply=0)

            serializers = NewQuestionSerializer(question, many=True)

        else:

            question = Question.objects.filter(labels=pk, reply=0)

            serializers = NewQuestionSerializer(question, many=True)

        return Response(serializers.data, status=status.HTTP_200_OK)


class PublishQuestionView(mixins.CreateModelMixin,GenericViewSet):
    '''发布问题'''

    permission_classes = [IsAuthenticated]

    serializer_class = PublishQuestionSerializers

    queryset = Question.objects.all()

    def create(self, request, *args, **kwargs):
        '''添加文章'''
        data = request.data
        data['user'] = request.user.id
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class ObtainDetailQuestionView(APIView):
    '''问题详情'''

    def get(self,request,pk):

        serializers = ObtainDetailQuestionSerializers(Question.objects.get(id=pk))

        return Response(serializers.data,status=status.HTTP_200_OK)



class UsefulQuestionView(mixins.UpdateModelMixin,GenericViewSet):
    '''问题有用/没用'''

    permission_classes = [IsAuthenticated]

    @action(methods=['put'],detail=True)
    def useful(self,request,pk):

        try:
            question = Question.objects.get(id=pk)

            if question.useful_count == 1:

                return Response({"message": "ok", "success": True}, status=status.HTTP_200_OK)

            question.useful_count = 1

            question.unuseful_count = 1

            question.save()

        except Exception:

            raise serializers.ValidationError('数据库写入出错')

        data = {"message": "ok", "success": True}

        return Response(data,status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def unuseful(self, request, pk):

        try:
            question = Question.objects.get(id=pk)

            if question.unuseful_count == 1:

                return Response({"message": "ok", "success": True}, status=status.HTTP_200_OK)

            question.unuseful_count = 1

            question.useful_count = 0

            question.save()

        except Exception:

            raise serializers.ValidationError('数据库写入出错')

        data = {"message": "ok", "success": True}

        return Response(data, status=status.HTTP_200_OK)

    lookup_value_regex = '\d+'



class ReplyQuestionView(APIView):
    '''回答问题'''

    permission_classes = [IsAuthenticated]

    def post(self,request):

        data = request.data

        data['user'] = request.user.id

        serializers = ReplyQuestionSerializers(data=data)

        serializers.is_valid(raise_exception=True)

        parent = data.get('parent', None)

        if not parent:

            try:

                Reply.objects.all().create(user_id=data.get('user'),problem_id=data.get('problem'),
                                                                    content=data.get('content'),
                                                                    type=data.get('type'),parent=parent)
                question = Question.objects.get(id=data.get('problem'))

                question.replyname = User.objects.get(id=request.user.id).username

                question.reply += 1

                question.replytime = timezone.now()

                question.save()

            except Exception:

                raise serializers.ValidationError('保存失败')

        else:

            try:

                reply = Reply.objects.all().create(user_id=data.get('user'), problem_id=data.get('problem'),
                                                   content=data.get('content'),
                                                   type=data.get('type'), parent=parent)
            except Exception:

                raise serializers.ValidationError('保存失败')

        return Response({"message": "ok", "success": True},status=status.HTTP_201_CREATED)


class UsefulReplyView(mixins.UpdateModelMixin,GenericViewSet):
    '''问题有用/没用'''

    permission_classes = [IsAuthenticated]

    @action(methods=['put'],detail=True)
    def useful(self,request,pk):

        try:
            reply = Reply.objects.get(id=pk)

            reply.useful_count = 1

            reply.unuseful_count = 1

            reply.save()

        except Exception:

            raise serializers.ValidationError('数据库写入出错')

        data = {"message": "ok", "success": True}

        return Response(data,status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def unuseful(self, request, pk):

        try:
            reply = Reply.objects.get(id=pk)

            reply.unuseful_count = 1

            reply.useful_count = 0

            reply.save()

        except Exception:

            raise serializers.ValidationError('数据库写入出错')

        data = {"message": "ok", "success": True}

        return Response(data, status=status.HTTP_200_OK)

    lookup_value_regex = '\d+'


class FocusLabelView(GenericViewSet):
    '''关注取消关注接口'''
    permission_classes = [IsAuthenticated]

    @action(methods=['put'], detail=True)
    def focusin(self,request,pk):
        '''关注'''
        label = Label.objects.get(id=pk)

        data = request.data

        data['user'] = request.user.id

        serializers = LabelSerializer(label,data = request.data)

        serializers.is_valid(raise_exception=True)

        serializers.save()

        return Response({"message": "ok", "success": True},status=status.HTTP_200_OK)


    @action(methods=['put'], detail=True)
    def focusout(self,request,pk):
        '''取消关注'''

        label = Label.objects.get(id=pk)

        data = request.data

        data['user'] = request.user.id

        serializer = LabelSerializer(label,data = request.data)

        serializer.is_valid(raise_exception=True)

        try:
            label = Label.objects.get(id=pk)

            label.users.remove(request.user.id)

        except Exception:

            raise serializers.ValidationError('数据库保存出错')

        return Response({"message": "ok", "success": True},status=status.HTTP_200_OK)

    lookup_value_regex = '\d+'


